package cc.abanlee.framework.web.core.handler;

import cc.abanlee.framework.common.pojo.CommonResult;
import cc.abanlee.framework.web.core.util.WebFrameworkUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author: create by 飞鱼
 * @version: v1.0
 * @description:
 * @date:2022/8/15
 */
@ControllerAdvice(basePackages = "cc.abanlee.module.system.controller")
public class GlobalResponseBodyHandler implements ResponseBodyAdvice {
    @Override
    @SuppressWarnings("NullableProblems") // 避免 IDEA 警告
    public boolean supports(MethodParameter returnType, Class converterType) {
        if (returnType.getMethod() == null) {
            return false;
        }
        // 只拦截返回结果为 CommonResult 类型
        return returnType.getMethod().getReturnType() == CommonResult.class;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        WebFrameworkUtils.setCommonResult(((ServletServerHttpRequest)request).getServletRequest(), (CommonResult<?>) body);
        return body;
    }
}
